package com.hoow.shakoow.base

import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import com.hoow.shakoow.components.dialog.LoadingDialog
import com.hoow.shakoow.components.dialog.MessageDialog
import com.hoow.shakoow.ai.network.NetworkException
import com.hoow.shakoow.launch.LaunchActivity
import com.hoow.shakoow.utils.UserStateUtil

abstract class BaseFragment : Fragment() {

    private lateinit var mLoadingDialog: LoadingDialog

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let {
            mLoadingDialog = LoadingDialog(it)
        }
        setViewModelActions()
    }

    /**绑定model*/
    protected abstract fun onBindingViewModel(): List<ViewModel>?

    private fun setViewModelActions() {
        val viewModelList = onBindingViewModel()
        if (!(viewModelList.isNullOrEmpty())) {
            viewModelList.forEach {
                if (it is BaseViewModelAction) {
                    it.getLoadingLiveData()
                        .observe(viewLifecycleOwner) { showLoading ->
                            if (showLoading)
                                showLodingDialog()
                            else
                                dismissLoadingDialog()
                        }

                    it.getNetworkExceptionLiveData()
                        .observe(viewLifecycleOwner) {
                            onHandleNetworkExcepton(it)
                        }
                }
            }
        }
    }

    protected fun showLodingDialog() {
        activity?.let {
            mLoadingDialog.showDialog(it)
        }
    }

    protected fun dismissLoadingDialog() {
        mLoadingDialog.dismissDialog()
    }

    /**交给子类去实现*/
    open fun onHandleNetworkExcepton(networkException: NetworkException) {
        activity?.let {
            if (networkException.isAlter()) {
                MessageDialog.showDialog(it.supportFragmentManager, networkException.msg) {
                    if (networkException.code.equals("401", true)) {
                        try {     // 清空token
                            UserStateUtil.saveToken("")

                            val curAct = requireActivity()
                            if (curAct is LaunchActivity) {
                                curAct.onRestarLaunch()
                            } else {
                                val intent =
                                    curAct.packageManager.getLaunchIntentForPackage(
                                        curAct.packageName
                                    )
                                intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                                startActivity(intent)
                                curAct.finish()
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            } else {
                Toast.makeText(it, networkException.msg, Toast.LENGTH_LONG)
                    .show()
            }
        }
    }

    /**交给子类去实现*/
    open fun requestSpecPermissions(permissionList: Array<String>) {
        try {
            (requireContext() as BaseActivity).requestSpecPermissions(
                permissionList
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /** 权限请求同意，交给子类去实现 */
    open fun onPermissionsRequestAllPass() {

    }

    /** 拍照成功返回-交给子类去实现 */
    open fun onTakePictureSuccess(localPath: String?, bitmap: Bitmap?) {

    }

    /** 打开相册选择照片成功返回-交给子类去实现 */
    open fun onOpenAblumSuccess(localPath: String?, bitmap: Bitmap?) {

    }

    /** 打开相册选择照片或拍照成功返回-交给子类去实现 */
    open fun onPickImageSuccess(localPath: String?, bitmap: Bitmap?, imgUrl: String?) {

    }

    /** 获取产口预参数返回-交给子类去实现 */
    open fun onFillPreParamsSuccess(imageUrl: String?, prompt: String?, negativePrompt: String?) {

    }

    /**
     * 所有数据是否录入完毕
     */
    open fun isAllFormDataFillCompleted(): Boolean {
        return true
    }
}